﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace WMS.Core
{
    public class Utils
    {
        public static long ConvertDateTimeToLong(DateTime dt)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            TimeSpan toNow = dt.Subtract(dtStart);
            long timeStamp = toNow.Ticks;
            timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
            return timeStamp;
        }

        /// <summary>
        /// 获取文件所以目录路径, 如果不存在则创建该目录.
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static string GetOrCreateDirectory(string filename, bool bCreate = true)
        {
            string path = Path.GetDirectoryName(filename);
            if (bCreate)
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            return path;
        }

        public static string GetSystem32Path()
        {
            return System32Path;
        }

        public static string AppPath
        {
            get
            {
                string appPath = AppDomain.CurrentDomain.BaseDirectory;
                if (!appPath.EndsWith("\\"))
                {
                    appPath += "\\";
                }
                return appPath;
            }
        }

        /// <summary>
        /// Window安装目录
        /// </summary>
        public static string WindowInstallPath
        {
            get
            {
                return Environment.GetFolderPath(Environment.SpecialFolder.Windows);
            }
        }

        /// <summary>
        /// Windows\System32目录
        /// </summary>
        public static string System32Path
        {
            get
            {
                return Path.Combine(WindowInstallPath, "System32");
            }
        }

        public static IEnumerable<string> GetCallers()
        {
            var stack = new StackTrace();
            for (var i = 0; i < stack.FrameCount; i++)
            {
                var m = stack.GetFrame(i);
                var filename = m.GetFileName();
                var pos = $"{m.GetFileLineNumber()},{m.GetFileColumnNumber()}";
                var mi = m.GetMethod();

                var moduleName = mi.Module.Name;
                var methodName = mi.Name;
                var scope = mi.IsPublic ? "public" : "private";
                var memberName = mi.GetType().FullName;

                var method = $"{scope} {memberName}.{methodName}()";
                var res = $"{filename}[{moduleName}]({pos})=> {method}.";
                yield return res;
            }
        }

    }

}
